<template>
  <div class="admin-home-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <i class="el-icon-s-goods stats-icon"></i>
            <div class="stats-content">
              <h3>待审商品</h3>
              <p class="number">{{ pendingGoods }}</p>
              <el-button 
                type="text" 
                @click="gotoGoodsReview"
                class="action-btn">
                立即处理 <i class="el-icon-arrow-right"></i>
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <i class="el-icon-s-order stats-icon"></i>
            <div class="stats-content">
              <h3>今日订单</h3>
              <p class="number">{{ todayOrders }}</p>
              <div class="compare">
                <span :class="orderTrend <=0 ? 'up' : 'down'">
                  {{ orderTrend }}% <i class="el-icon-top"></i>
                </span>
                较昨日
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <i class="el-icon-user-solid stats-icon"></i>
            <div class="stats-content">
              <h3>新增用户</h3>
              <p class="number">{{ newUsers }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 报表导出控制区域 -->
    <el-row :gutter="20" class="export-row">
      <el-col :span="24">
        <el-card>
          <div class="export-controls">
            <el-date-picker
              v-model="exportDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              class="date-range-picker">
            </el-date-picker>
            
            <el-select 
              v-model="exportType" 
              placeholder="选择报表类型"
              class="export-type-select">
              <el-option
                v-for="item in exportOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            
            <el-button 
              type="primary" 
              icon="el-icon-download"
              @click="exportReport"
              :loading="exportLoading"
              class="export-btn">
              导出报表
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据可视化区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card>
          <h4 class="chart-title">交易趋势分析</h4>
          <div id="salesChart" style="height: 320px;"></div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card>
          <h4 class="chart-title">商品分类占比</h4>
          <div id="categoryChart" style="height: 320px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
name: "admin-index",
data() {
  return {
    // 统计数据
    pendingGoods: 0,
    todayOrders: 0,
    orderTrend: 0,
    newUsers: 0,
    
    // 导出相关数据
    exportDateRange: [],
    exportType: 'all',
    exportLoading: false,
    exportOptions: [
      { value: 'all', label: '全部数据' },
      { value: 'orders', label: '订单数据' },
      { value: 'users', label: '用户数据' },
      { value: 'goods', label: '商品数据' }
    ]
  }
},
mounted() {
  this.initCharts();
},
methods: {
  gotoGoodsReview() {
    this.$router.push({
      path: '/platform-admin',
      query: { mode: '5' },
    });
  },

  async initCharts() {
    try {
      this.$api.getChartsInfo({page: this.nowPage, nums: 8}).then(res => {
        this.pendingGoods = res.data.pendingGoods;
        this.todayOrders = res.data.todayOrders; 
        this.orderTrend = res.data.orderTrend; 
        this.newUsers = res.data.newUsers;

        // 销售趋势图
        const salesChartDom = document.getElementById('salesChart');
        if (salesChartDom) {
          const salesChart = echarts.init(salesChartDom);
          const dates = res.data.nearly7Days || [];
          const salesData = res.data.nearly7DaysSales || [];
          
          salesChart.setOption({
            xAxis: {
              type: 'category',
              data: dates,
            },
            yAxis: { type: 'value' },
            series: [{
              data: salesData,
              type: 'line',
              smooth: true,
              areaStyle: {}
            }]
          });
        }
        
        // 商品分类图
        const categoryChartDom = document.getElementById('categoryChart');
        if (categoryChartDom) {
          const categoryChart = echarts.init(categoryChartDom);
          const categoryNames = res.data.categoryName || [];
          const categoryCounts = res.data.categoryCount || [];
          const chartData = categoryNames.map((name, index) => ({
            name,
            value: categoryCounts[index] || 0
          }));

          if (chartData.length === 0) {
            chartData.push({ name: '暂无数据', value: 1 });
          }

          categoryChart.setOption({
            tooltip: {
              trigger: 'item',
              formatter: ({ name, value, percent }) => 
                `${name}<br/>数量：${value}件<br/>占比：${percent}%`
            },
            series: [{
              type: 'pie',
              radius: ['45%', '40%'],
              data: chartData,
              label: {
                show: true,
                formatter: ({ name, percent }) => 
                  `${name}\n${percent}%`
              },
              itemStyle: {
                borderRadius: 9,
                borderColor: '#fff',
                borderWidth: 2
              }
            }]
          });
        }
      });
    } catch (error) {
      console.error('初始化图表失败:', error);
    }
  },
  
  async exportReport() {
  if (!this.exportDateRange || this.exportDateRange.length !== 2) {
    this.$message.warning('请选择日期范围');
    return;
  }
  
  this.exportLoading = true;
  try {
    const [startDate, endDate] = this.exportDateRange;
    
    // 修改请求配置，指定响应类型为blob
    const response = await this.$api.exportReport({
      startDate,
      endDate,
      type: this.exportType
    }, {
      responseType: 'blob' // 添加这一行
    });
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `报表_${startDate}_至_${endDate}.xlsx`);
    document.body.appendChild(link);
    link.click();
    
    // 清理资源
    setTimeout(() => {
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    }, 100);
    
    this.$message.success('报表导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    this.$message.error('报表导出失败: ' + (error.response.data.message || '请稍后重试'));
  } finally {
    this.exportLoading = false;
  }
}
},
filters: {
  statusColor(type) {
    const map = {
      '商品审核': 'warning',
      '投诉处理': 'danger'
    }
    return map[type] || 'info'
  }
}
}
</script>

<style scoped>
.admin-home-container {
padding: 20px;
}

/* 统计卡片样式 */
.admin-home-container .stats-row {
margin-bottom: 20px;
}

.admin-home-container .stats-row .stats-card {
border-radius: 8px;
border: none;
box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.admin-home-container .stats-row .stats-card .stats-item {
display: flex;
align-items: center;
padding: 15px;
}

.admin-home-container .stats-row .stats-card .stats-item .stats-icon {
font-size: 40px;
margin-right: 20px;
color: #409EFF;
}

.admin-home-container .stats-row .stats-card .stats-item .stats-content h3 {
margin: 0 0 8px;
font-size: 16px;
color: #666;
}

.admin-home-container .stats-row .stats-card .stats-item .stats-content .number {
font-size: 24px;
font-weight: bold;
margin: 8px 0;
}

.admin-home-container .stats-row .stats-card .stats-item .stats-content .compare {
font-size: 12px;
color: #999;
}

.admin-home-container .stats-row .stats-card .stats-item .stats-content .compare .up {
color: #67c23a;
}

.admin-home-container .stats-row .stats-card .stats-item .stats-content .compare .down {
color: #f56c6c;
}

.admin-home-container .stats-row .stats-card .stats-item .stats-content .action-btn {
padding: 0;
margin-top: 8px;
}

/* 导出控制区域样式 */
.export-row {
margin-bottom: 20px;
}

.export-controls {
display: flex;
align-items: center;
gap: 15px;
padding: 10px;
}

.date-range-picker {
width: 350px;
}

.export-btn {
padding: 10px 20px;
}

.export-type-select {
width: 200px;
}

/* 图表区域样式 */
.admin-home-container .chart-row {
margin-bottom: 20px;
}

.admin-home-container .chart-row .chart-title {
color: #666;
margin: 0 0 15px;
font-size: 16px;
font-weight: 500;
}

</style>